//
//  IntegralDetailVC.swift
//  LeGou
//
//  Created by 刘亿前 on 2022/10/20.
//

import UIKit

class IntegralDetailVC: ZMViewController {
    //MARK: --------------------属性--------------------
    var sectionVcs = [UIViewController]()
    // 分栏title
    var getTitles : [(String, String)] {
        return [("收入", "1"), ("支出", "0")]
    }
    
    var info = ZMUtil.fastNilBehavior(type: VIPMallModels.BalanceInfo.self)
    
    //MARK: --------------------UI控件--------------------
    var headerContentView = UIView()
    var seg : XMIndexHeaderView!
    var contentView = UIView()
    var childVCCollectioView : UICollectionView!
    
    var header = IntegralDashView().then({$0.layer.cornerRadius = 12; $0.layer.masksToBounds = true;})
    
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadInfo()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        ZMUtil.clipCircle(view: headerContentView, Corner: [.topLeft, .topRight], radius: 12)
    }
    //MARK: --------------------UI--------------------
    func setUI() {
        title = "积分明细"
        view.addSubview(header)
        view.addSubview(headerContentView)
        view.addSubview(contentView)
        makeSeg()
        makeColletionView()
        configData()
        view.backgroundColor = "#F5F5F5".zm.hex()
    }
    
    func addConstraints() {
        header.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(rpx(146))
        }
        
        headerContentView.snp.makeConstraints { make in
            make.top.equalTo(header.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(44)
        }
        contentView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.top.equalTo(headerContentView.snp.bottom).offset(1)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        
        childVCCollectioView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    func makeSeg() {
        let config  = XMIndexHeaerViewConfig()
        config.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        config.fontColor  = UIColor.zm.color999999()
        config.selectFont = UIFont.systemFont(ofSize: 16, weight: .medium)
        config.selectFontColr = Style.mainColor
        config.lineViewCornerRadius = 1.5
       
        seg = XMIndexHeaderView(frame: CGRect(x: 0, y: 0, width: SCREEN_W - 30, height: 44), withTitleArray:getTitles.map({$0.0}), animation: false)!
        seg.lineColor = Style.mainColor
        seg.lineWidth = 17
        seg.config = config
        seg.delegateXM = self
        headerContentView.addSubview(seg!)
    }
    
    func makeColletionView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        childVCCollectioView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_W, height: 100), collectionViewLayout: layout)
        childVCCollectioView.delegate = self
        childVCCollectioView.dataSource = self
        contentView.addSubview(childVCCollectioView)
        childVCCollectioView.tag = 999
        childVCCollectioView.isPagingEnabled = true
        childVCCollectioView.backgroundColor = .clear
        childVCCollectioView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        childVCCollectioView.showsHorizontalScrollIndicator = false
    }
    
    //MARK: --------------------methods--------------------
    func configData() {
        for cate in getTitles {
            let vc = IntegralDetailListVC()
            vc.type = cate.1
            addChild(vc)
            sectionVcs.append(vc)
        }
    }
    
    func bindAction() {
        header.auctionBtn.onClick = { [weak self] in
            guard let self = self else {return}
            let vc = IntegralExchange()
            vc.type = 1
            vc.optionSuccessBlock = {[weak self] _ in
                guard let self = self else {return}
                for fooVc in self.sectionVcs {
                    if let listVc = fooVc as? IntegralDetailListVC {
                        listVc.tableView.mj_header?.beginRefreshing()
                    }
                }
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        header.quotaBtn.onClick = { [weak self] in
            guard let self = self else {return}
            let vc = IntegralExchange()
            vc.type = 2
            vc.optionSuccessBlock = {[weak self] _ in
                guard let self = self else {return}
                for fooVc in self.sectionVcs {
                    if let listVc = fooVc as? IntegralDetailListVC {
                        listVc.tableView.mj_header?.beginRefreshing()
                    }
                }
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        info.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {
                self.header.value.text = ""
                return
            }
            self.header.value.text = resp.integral.zm.toString(keep: 4)
        }).disposed(by: disposeBag)
    }
    
    func loadInfo() {
        VIPMallAPI.mallIncomeInfo([:]).rxRequest(type:VIPMallModels.BalanceInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.info.accept(resp)
            
        }, onError: { e in
            
        }).disposed(by: disposeBag)
    }
}

//MARK: --------------------delegate--------------------
extension IntegralDetailVC : XMIndexHeaderViewDelegate {
    func xmIndexHeaderViewDidselected(with index: Int) {
        childVCCollectioView.setContentOffset(CGPoint(x: CGFloat(index) * contentView.zm.size.width, y: 0), animated: true)
    }
}

extension IntegralDetailVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        sectionVcs.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        cell.contentView.subviews.forEach({$0.removeFromSuperview()})
        let v = sectionVcs[indexPath.row]
        cell.contentView.addSubview(v.view)
        v.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.zm.size
    }
        
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !(scrollView.isTracking || scrollView.isDecelerating) {
            return;
        }
        var index = Int(scrollView.contentOffset.x / scrollView.zm.width)
        
        if (Int(scrollView.contentOffset.x) % Int(scrollView.zm.width)) > Int(scrollView.zm.width / 2) {
            index += 1
        }
        seg.lineViewScrolle(to: index)
    }
}

extension IntegralDetailVC {
    class IntegralDashView : UIView {
        static let mainColor = "#5E2F03".zm.hex()
        
        let wdjf = ZMUtil.label(title: "我的积分", color: IntegralDashView.mainColor, font: UIFont.systemFont(ofSize: 14, weight: .medium))
        
        let value = ZMUtil.label(title: "0.0", color: IntegralDashView.mainColor, font: Style.FONT_Open_Sans_SemiBold(36))
        
        let auctionBtn = ImageRightButton(config: ImageRightButton.Config(imageName: "icon_right_small", title: "兑换竞购次数", font: UIFont.systemFont(ofSize: 12, weight: .medium), color: IntegralDashView.mainColor), frame: CGRect.zero).then { b in
            b.image.tintColor = IntegralDashView.mainColor
        }
        
        let quotaBtn = ImageRightButton(config: ImageRightButton.Config(imageName: "icon_right_small", title: "兑换出局额度", font: UIFont.systemFont(ofSize: 12, weight: .medium), color: IntegralDashView.mainColor), frame: CGRect.zero).then { b in
            b.image.tintColor = IntegralDashView.mainColor
        }
        
        let bottomStack = ZMUtil.stackView(axis: .horizontal)
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
            
        }
        
        required init?(coder: NSCoder) {
            super.init(coder: coder)
            setUI()
        }
        
        func setUI() {
            backgroundColor = "#FFEA34".zm.hex()
            
            addSubview(wdjf)
            addSubview(value)
            
            bottomStack.addArrangedSubview(auctionBtn)
            bottomStack.addArrangedSubview(quotaBtn)
            addSubview(bottomStack)
            bottomStack.distribution = .equalSpacing
            
            wdjf.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(16)
                make.top.equalToSuperview().offset(16)
            }
            
            value.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(16)
                make.top.equalTo(wdjf.snp.bottom).offset(4)
            }
            
            bottomStack.snp.makeConstraints { make in
                make.bottom.equalToSuperview().offset(20)
                make.left.equalToSuperview().offset(rpx(45))
                make.right.equalToSuperview().offset(rpx(-45))
                make.height.equalTo(100)
            }
        }
    }
}



class ImageRightButton : UIView {
    struct Config {
        var imageName : String
        var title : String
        var font : UIFont
        var color : UIColor
        var space : CGFloat = 5
        var location : ImageButtonLocation = .right
    }
    
    enum ImageButtonLocation {
        case top
        case bottom
        case left
        case right
    }
    
    let image = UIImageView()
    let title = UILabel()
    let stack = ZMUtil.stackView(axis: .horizontal)
    var config : Config!
    
    var onClick : (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    init(config : Config, frame : CGRect) {
        super.init(frame: frame)
        self.config = config
        setUI()
        _ = zm.addTapGestureRecognizer(target: self, action: #selector(onSelfClick))
    }
    
    func setUI() {
        if config.location == .right {
            stack.distribution = .fillProportionally
            stack.addArrangedSubview(title)
            stack.addArrangedSubview(image)
            stack.spacing = config.space
            title.font = config.font
            title.textColor = config.color
            title.text = config.title
            image.image = UIImage.init(named: config.imageName)
            stack.spacing = config.space
            stack.alignment = .center
        }
        
        title.sizeToFit()
        image.sizeToFit()
        
        addSubview(stack)
        stack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
//            make.width.height.equalTo(100)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }
    
    @objc func onSelfClick() {
        if let onClick = onClick {
            onClick()
        }
    }
}

